layui.use(['form', 'layer', 'jquery'], function () {

  let editor_content = ''
  let post_type = ''

  var form = layui.form
  var $ = layui.jquery
  let now = new Date().getTime()

  try {
    var editor_md = editormd('bbd-mdedit', {
        width: '100%',
        height: '54vh',
        path: '/static/editor.md-master/lib/',
        imageUpload: true,
        imageFormats: ['jpg', 'jpeg', 'gif', 'png', 'bmp'],
        imageUploadURL: `/mdeditor/uploads/?guid=${now}`,
      }
    )
    editor_content = function () {
      return editor_md.getMarkdown()
    }
    post_type = 'md'
  } catch (e) {
    tinymce.init({
      selector: '#bbd-layedit',
      language: 'zh_CN',
      height: '54vh',
      plugins: 'codesample image',
      toolbar: ' bold  italic  underline  strikethrough | alignleft aligncenter alignright alignjustify | styleselect fontselect fontsizeselect bullist | numlist outdent | indent | blockquote | undo | redo | subscript | superscript | link image | codesample',
      menubar: false,
      // codesample_content_css: '/static/js/lib/prism/prism-okaidia.css',
      images_upload_url: `/upload/`,
      automatic_uploads: false
    })

    editor_content = function () {
      return tinymce.activeEditor.getContent()
    }
  }

  form.render()

  form.on('submit(article_edit)', function (data) {
    data.field.editor_content = editor_content()
    if (post_type && post_type == 'md') {
      data.field.md = true
    } else {
      data.field.md = false
    }

    console.log(data.field)
    axios.post('/edit/' + data.field.article_id, data.field, {
      headers: {
        'X-CSRFToken': CsrfToken()
      }
    }).then(function (res) {
      $('#edit_message').html(res.data.message).fadeIn()
      if (res.data.action === 'submit') {
        window.location.href = '/article_detail/' + res.data.article_id + '.html'
      }
    }).catch(function (error) {
      console.log(error)
    })
    return false
  })
})